package com.wis.bolt.common;

import com.alibaba.fastjson.JSONObject;
import com.wis.tools.CommonUtiles;
import org.apache.commons.lang.StringUtils;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.Map;

/**
 * @Description: traffic_wis
 * @author: z1042
 * @Date: Created in 2018/12/13 20:13
 * @Modified By:
 */
public class QiePianDianBolt extends BaseRichBolt {
    private OutputCollector collector;
    private String tmpSlice = new String();
    private JSONObject jsonQiePian;

    @Override
    public void prepare(Map map, TopologyContext topologyContext, OutputCollector collector) {
        this.collector = collector;
        jsonQiePian = new CommonUtiles().getHttpJsonObject(map.get("queryPointSclie").toString()  );
    }

    @Override
    public void execute(Tuple tuple) {
        String key = tuple.getStringByField("key");
        String value = tuple.getStringByField("value");
        try {
            if (StringUtils.isNotBlank(value) && value.length() > 4) {
                String[] lines = value.split(",", 2);
                if (StringUtils.isNotBlank(tmpSlice) && !jsonQiePian.get(lines[0]).equals(tmpSlice)) {
                    this.collector.emit(new Values(key + "sc" + tmpSlice, "over"));
                }
                tmpSlice = (String) jsonQiePian.get(lines[0]);
                this.collector.emit(new Values(key + "sc" + tmpSlice, value));
            } else if (value.equals("over")) {
                this.collector.emit(new Values(key + "sc" + tmpSlice, "over"));
            } else if (value.equals("jies")) {
                this.collector.emit(new Values(key + "sc" + tmpSlice, "jies"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.collector.ack(tuple);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("key", "value"));
    }
}
